<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户" prop="customerId">
        <!--        <el-input-->
        <!--          v-model="queryParams.customerId"-->
        <!--          placeholder="请输入客户编号"-->
        <!--          clearable-->
        <!--          @keyup.enter="handleQuery"-->
        <!--          class="!w-240px"-->
        <!--        />-->
        <el-select
          v-model="queryParams.customerId"
          clearable
          filterable
          placeholder="请选择客户"
          class="!w-40"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:inquiry-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          @click="handleExport"-->
        <!--          :loading="exportLoading"-->
        <!--          v-hasPermi="['erp:inquiry-order:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:download" class="mr-5px"/>-->
        <!--          导出-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" border :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="订单编号" align="center" prop="id"/>-->
      <el-table-column
        label="订单时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="120px"
      />
      <el-table-column label="客户" prop="customerName" width="120"/>
      <el-table-column label="VIN" prop="product.vin" width="180"/>
      <el-table-column label="车型" prop="product.carType" width="200"/>
      <el-table-column label="品牌" align="center" prop="product.brandName" width="90"/>
      <el-table-column label="工厂名称" prop="product.factoryName" width="180"/>
      <el-table-column label="库存" prop="count"/>
      <!--      <el-table-column label="产品名称"  prop="product.name" width="260"/>-->
      <el-table-column label="报价" prop="orderPrice" width="70"/>

      <el-table-column label="参考报价" prop="historyPrice" width="120">
        <template #default="scope">
          <el-button
            link
            v-for="(value, index) in scope.row.priceList" :key="index"
            type="primary"
            @click="openHistoryPriceDetail(scope.row.productId)"
          >
            <el-tag  type="success">
              {{value}}
            </el-tag>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="订单编号" align="center" prop="no" width="200"/>
      <el-table-column label="状态" align="center" fixed="right" prop="destOrderId" width="90">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.destOrderId != null">已生成</el-tag>
          <el-tag type="warning" v-else>未生成</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" fixed="right" align="center" width="280">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:inquiry-order:update']"
          >
            编辑
          </el-button>

          <el-button
            link
            @click="handleSyncOrder(scope.row,'销售单')"
            type="primary"
            v-hasPermi="['erp:inquiry-order:delete']"
          >
            销售单
          </el-button>
          <el-button
            link
            disabled
            type="danger"
            v-hasPermi="['erp:inquiry-order:delete']"
          >
            采购单
          </el-button>
          <el-button
            link
            disabled
            type="danger"
            v-hasPermi="['erp:inquiry-order:delete']"
          >
            派单
          </el-button>

          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:inquiry-order:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!--  历史价格详情-->
  <el-dialog
    v-model="historyPriceDetailVisible"
    title="参考报价"
    width="40%"
  >
  <el-tag class="mr-3" v-for="(value, key, index) in mapPrice" :key="index">【{{key}}】{{value}}</el-tag>
    <el-table v-loading="historyPriceLoading" :data="historyPriceList" border :stripe="true"
              :show-overflow-tooltip="true">
      <el-table-column label="客户名称" align="center" prop="custName"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="订单时间" align="center" prop="orderTime"
                       :formatter="dateFormatter2"/>
      <el-table-column label="价格" align="center" prop="orderPrice"/>
    </el-table>

  </el-dialog>


  <!-- 表单弹窗：添加/修改 -->
  <InquiryOrderForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import {InquiryOrderApi, InquiryOrderVO} from '@/api/erp/inquiryorder'
import InquiryOrderForm from './InquiryOrderForm.vue'

import {CustomerApi, CustomerVO} from "@/api/erp/sale/customer";
import {ElLoading} from "element-plus";

const customerList = ref<CustomerVO[]>([]) // 客户列表
/** 询价订单 列表 */
defineOptions({name: 'InquiryOrder'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const historyPriceLoading = ref(true) // 列表的加载中
const historyPriceDetailVisible = ref(false) // 历史价格详情
const historyPriceList = ref([]) // 历史价格详情
const list = ref<InquiryOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  remark: undefined,
  status: undefined,
  sort: undefined,
  createTime: [],
  productId: undefined,
  customerId: undefined,
})
const mapPrice = ref();
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InquiryOrderApi.getInquiryOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}


const handleSyncOrder = async (row, type: string) => {

  if (row.destOrderId != null){
    message.error("该订单已生成"+type+"单");
    return;
  }

  let id = row.id;
  let loading;
  try {
    // 二次确认
    await message.confirm(t('确认生成'+type+'吗？'));

    loading = ElLoading.service({
      lock: true,
      text: '生成中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    // 发起
    await InquiryOrderApi.syncOrder(id)
    message.success(t('生成成功'))
    // 刷新列表
    await getList()

  } finally {
    loading.close()
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InquiryOrderApi.deleteInquiryOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

//查看价格详情
const openHistoryPriceDetail = async (productId: number) => {
  historyPriceLoading.value = true;
  historyPriceList.value = [];
  historyPriceDetailVisible.value = true;
  let r = await InquiryOrderApi.historyPriceDetail(productId)
  historyPriceList.value = r.list;
  mapPrice.value = r.mapPrice;
  historyPriceLoading.value = false;
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InquiryOrderApi.exportInquiryOrder(queryParams)
    download.excel(data, '询价订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted ? onMounted(async () => {

  // 加载客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()

  await getList()
}) : null
onActivated ? onActivated(() => {
  getList()
}) : null
</script>
